/**
 * Copyright(c) 2014 Xunton Solutions
 *
 * History:
 *   15-5-11 下午2:27 Created by dwzhang
 */
package com.jade.bss.business.order.valve;

import java.util.List;

import com.jade.bss.base.BssException;
import com.jade.bss.base.customer.Customer;
import com.jade.bss.business.order.Order;
import com.jade.bss.business.order.OrderContext;
import com.jade.bss.business.order.OrderItem;
import com.jade.bss.base.product.Product;
import com.jade.bss.base.product.ProductConstants;
import com.jade.bss.base.subs.SubsConstants;
import com.jade.bss.base.subs.Subscription;

/**
 * 订单支付完成以后，如果是增值类产品，需要创建或者更新订购关系。
 *
 * @author <a href="mailto:dwzhang@xunton.com">dwzhang</a> 
 * @version 1.0 15-5-11 下午2:27
 */
public class UpdateSubsValve
        extends AbstractOrderValve
{
    protected void doHandle(OrderContext context)
            throws BssException
    {
        Order order = context.getOrder();
        List<OrderItem> items = order.getItems();
        Customer customer = customerManager.getCustomer(order.getCustomerId());
        for (OrderItem item : items) {
            long productId = item.getProductId();
            Product product = productManager.getProduct(productId);
            if (product.getType() == ProductConstants.PRODUCT_TYPE_FIXED) {
                //非基础产品和增值产品
                continue;
            }
            Subscription subs = subsManager.getSubs(order.getCustomerId(), productId);
            if (subs != null) {
                //已经订购，延长使用时间
                //todo get mode
                subsManager.renewSubs(subs.getId(), item.getCount(), null, SubsConstants.MODE_WEB);
            }
            else {
                //没有订购，创建订购关系
                //todo get mode
                subsManager.subscribe(customer, product, item.getCount(), null, SubsConstants.MODE_WEB);
            }
        }
    }
}
